// +----------------------------------------------------------------------
// | CmsWing [ 美业管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 psi All rights reserved.
// +----------------------------------------------------------------------
// | Author: huang <2374266244@qq.com>
// +----------------------------------------------------------------------
'use strict';
import Base from './base.js';

export default class extends Base {

	async categorylistAction(){
		let shopid = this.userinfo.departmentid;
		let plist = await this.model().query('SELECT * FROM think_or_subjectcategory WHERE departmentid='+shopid+' AND pid=0');
		let clist = await this.model().query('SELECT * FROM think_or_subjectcategory WHERE departmentid='+shopid+' AND pid!=0');
		let data = {
			p: plist,
			c: clist
		}
		return this.json(data);
	}

	// 添加、编辑
	async addeditAction(){
		let row = this.post();
		let orid = this.userinfo.departmentid;
		let addtime = Math.round(new Date().valueOf()/1000);

		if (row.id*1) {
			let repeat = await this.model('or_subjectcategory').where({name:row.name,departmentid:row.departmentid,id:['!=',row.id]}).find();
			if(!think.isEmpty(repeat)){
				return this.fail("此项目分类已经存在");
			}
			let res = await this.model('or_subjectcategory').where({id: row.id}).update({name: row.name});
			return res?this.success("编辑成功"):this.fail("编辑失败");
		}

		let chongfu = await this.model('or_subjectcategory').where({name:row.name,departmentid:orid}).find();
		if(!think.isEmpty(chongfu)){
			return this.fail("此项目分类已经存在");
		}

		row.departmentid = orid;
		row.addtime = addtime;

		let addmsg = await this.model('or_subjectcategory').add(row);
		return addmsg?this.success('新增成功'):this.fail('新增失败');
	}

	// 启用、停用项目分类 -> 该项目分类下的所有项目都停用或启用
	async disablesubjectcategoryAction(){
		let id = this.post('id');
		let isdisable = this.post('isdisable');
		let res = await this.model('or_subjectcategory').where({id:id}).update({isdisable:isdisable});
		let disabledsubject = await this.model('or_subject').where({categoryid:id}).update({isdisable:isdisable});

		if (isdisable == 0) {
			return res? this.success({info:'启用成功'}) : this.fail('启用失败');
		} else if (isdisable == 1) {
			return res? this.success({info:'停用成功'}) : this.fail('停用失败');
		}
	}


	// 机构客户分类
	async getguestcategoryAction(){
		let orid = this.userinfo.departmentid;
		let data = await this.model('or_guestcategory').where({departmentid: orid}).find();
		return this.json(data);
	}

	// 设置机构客户分类信息
	async setguestcategoryAction(){
		let data = JSON.parse(this.post('data'));

		data.departmentid = this.userinfo.departmentid;
		if (!data.id) {
			data.id = 0;
		}
		let res = await this.model('or_guestcategory').where({id: data.id}).thenUpdate(data);

		return res?this.success('修改成功'):this.fail('修改失败');
	}
}